package com.myserver.core;

import com.myserver.log.LoggerFactory;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class Request {
    private String method;// 请求方法
    private String url;//请求路径
    private Map<String,String> requetsParam;
    private InputStream is;
    private static final String CRLF = "\r\n";
    private static final String SPACE = " ";
    final Logger logger = LoggerFactory.getLogger();
    public Request(InputStream is){
        this.is = is;
        requetsParam = new HashMap<>();
        parseReqInfo();
    }
    private void parseReqInfo() {
        byte[] data = new byte[2048];
        int len = 0;
        try {
            len = is.read(data);
            if (len == -1)
                return;
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*请求信息*/
        String reqInfo = new String(data, 0, len).trim();
        /*首行信息*/
        String firstLine = reqInfo.substring(0, reqInfo.indexOf(CRLF));
        String[] str = firstLine.split(" ");
        /*请求方法*/
        this.method = str[0].trim();
        /*请求路径*/
        String reqUrl = str[1];
        logger.info("请求路径:"+reqUrl);
        String paramStr = "";
         /*解析get方法参数*/
        if (method.equalsIgnoreCase("get")) {
            if(reqUrl.contains("?")) {
                paramStr = reqUrl.substring(reqUrl.indexOf("?")+1);
            }
        }
        /*解析post*/
        else if(method.equalsIgnoreCase("post")) {
            paramStr = reqInfo.substring(reqInfo.lastIndexOf(CRLF)+2);
        }
        /*有参数时请求路径*/
        if(reqUrl.contains("?")){
            this.url = reqUrl.substring(0,reqUrl.indexOf("?"));
        }
        /*无参数时请求路径*/
        else {
            logger.info(reqUrl);
            this.url = reqUrl;
            return;
        }
        parseParam(paramStr);
    }
    private void parseParam(String paramString){
        String[] str = paramString.split("&");
        for(int i=0;i<str.length;i++){
            String[] s = str[i].split("=");
            requetsParam.put(s[0],s[1]);
        }
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, String> getRequetsParam() {
        return requetsParam;
    }

    public void setRequetsParam(Map<String, String> requetsParam) {
        this.requetsParam = requetsParam;
    }
}
